<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
 * @property admin_model $admin_model
 * @author kekeyumuku
 * @property Auth  $auth
 */
class Manage extends CT_Controller
{
    function __construct()
    {
        parent::__construct();
        $this->load->model('admin_model');
        $this->load->model('role_model');
    }

    /**
     * 管理员列表
     *
     */
    public function index()
    {
        $page = $this->input->get('per_page',TRUE) ? $this->input->get('per_page',TRUE) : 1;
        $pagesize = 1;//$this->config->item('per_page')?$this->config->item('per_page'):20;
        $offset = ($page-1) * $pagesize;
        $condition = array();
        //获取总数
        $this->admin_model->findAll( $condition,null,null,null,null);
        $total =$this->admin_model->__numRows;
        $admin_all = $this->admin_model->get_list($condition,$offset,$pagesize);
        $pagelink = $this->pagination($total,$pagesize);
        $data['pagelink'] = $pagelink;
        $data['admin_all'] = $admin_all;
        $data['_title'] ='管理员列表';

        $this->ct_template->write('_title', '管理员列表');
        $this->ct_template->write('breadcrum', '管理员列表');

        $this->ct_template->write_view('content', 'admin/manage/index', $data, false);
        $this->ct_template->render();
    }


    /**
     * 管理员添加
     */

    function add()
    {
        //表单验证
        $this->lang->load('form_validation', 'chinese');
        $this->load->helper('form');
        $this->load->library('form_validation');
        $data = array( );
        $this->form_validation->set_rules('username', '用户名', 'required');
        $this->form_validation->set_rules('pass', '密码', 'required');
        $this->form_validation->set_rules('rid', '管理员角色', 'required');
        if( $this->form_validation->run() != FALSE ){

            $username = $this->input->post('username',TRUE);
            $nickname = $this->input->post('nickname',TRUE);
            $pass = $this->input->post('pass',TRUE);

            
            $pattern="/^[\x{4e00}-\x{9fa5}a-zA-Z0-9_\-]+$/u";
            if(! preg_match($pattern,$username)){
                $alerts = array('error' => '添加失败，名称存在非法字符！');
                $this->common_jump_url($alerts);
            }
            

            //验证管理员名称是否重复存在
            $check_res=$this->admin_model->check_admin_name($username,NULL);
            if(!empty($check_res))
            {
                $alerts = array('error' => '添加失败，管理员名称已存在！');
                $this->common_jump_url($alerts);

            }

            //如果用户填写了昵称字段，那么验证管理员昵称是否重复存在
            if(!empty($nickname))
            {
                $check_res=$this->admin_model->check_admin_nickname($nickname,NULL);
                if(!empty($check_res))
                {
                    $alerts = array('error' => '添加失败，管理员昵称已存在！');
                    $this->common_jump_url($alerts);
                }

            }

            //验证密码格式是否正确
            if(strlen($pass)<6 || strlen($pass)>30){

                $alerts = array('error' => '添加失败，密码长度不能小于6位或者大于30位！');
                $this->common_jump_url($alerts);
            }

            $this->load->library('CT_auth');

            $rid = $this->input->post('rid',TRUE);
            $password = $this->ct_auth->hashSSHA($pass);
            $data = array(
                    'username'=>$username,
                    'nickname'=>$nickname,
                    'pass'=>$password,
                    'rid'=>$rid
            );
            $this->admin_model->insert($data);
            $alerts = array('success' => '添加管理员成功');
            $this->common_jump_url($alerts,'/admin/manage');

        }
        $data['_title'] ='添加管理员';
        $this->ct_template->write('_title', '管理员添加');
        $this->ct_template->write('breadcrum', '管理员添加');
        //获取所有的角色(排除超级管理员的角色)
        $condition['name <>']='超级管理员';
        $data['roles'] = $this->role_model->findAll($condition);
        $this->ct_template->write_view('content', 'admin/manage/add', $data, false);
        $this->ct_template->render();
    }


    /**
     * 管理员编辑
     * @param $id
     */


    function edit($id)
    {
       //表单验证
        $this->lang->load('form_validation', 'chinese');
        $this->load->helper('form');
        $this->load->library('form_validation');
        $data = array( );
        $row = $this->admin_model->find( array('id'=>$id));
        $data['result'] = $row;
        $this->form_validation->set_rules('username', '用户名', 'required');
        if ( $this->form_validation->run() != FALSE )
        {
            $this->load->library('CT_auth');
            $id = $this->input->post('id',TRUE);
            $username = $this->input->post('username',TRUE);
            $nickname = $this->input->post('nickname',TRUE);

            //判断名称中是否有特殊字符
            $pattern="/^[\x{4e00}-\x{9fa5}a-zA-Z0-9_\-]+$/u";
            if(! preg_match($pattern,$username))
            {
                $alerts = array('error' => '修改失败，名称存在非法字符！');
                $this->common_jump_url($alerts);
            }
            
            $pass = $this->input->post('pass',TRUE);
            $rid = $this->input->post('rid',TRUE);

            $role_res=$this->role_model->find(array('id'=>$row['rid']));
            if($role_res['name']==='超级管理员')
            {
                $alerts = array('error' => '超级管理员不能够被编辑！');
                $this->common_jump_url($alerts,'/admin/manage');
            }

            $data = array(
                        'username'=>$username,
                        'nickname'=>$nickname,
                        'rid'=>$rid,
                        'update_time'=>date('Y-m-d H:i:s')
                    );

            //验证管理员名称是否重复存在
            $check_res=$this->admin_model->check_admin_name($username,$id);
            if(!empty($check_res))
            {
                $alerts = array('error' => '修改失败，管理员名称已存在！');
                $this->common_jump_url($alerts);

            }

            //如果用户尝试修改密码
            if( !empty($pass) )
            {
                //验证密码格式是否正确
                if(strlen($pass)<6 || strlen($pass)>30){

                    $alerts = array('error' => '修改失败，密码长度不能小于6位或者大于30位！');
                    $this->common_jump_url($alerts);
                }
                $pass = $this->ct_auth->hashSSHA($pass);
                $data['pass'] = $pass;
            }

            //如果用户填写了昵称字段，那么验证管理员昵称是否重复存在
            if(!empty($nickname))
            {
                $check_res=$this->admin_model->check_admin_nickname($nickname,$id);
                if(!empty($check_res))
                {
                    $alerts = array('error' => '修改失败，管理员昵称已存在！');
                    $this->common_jump_url($alerts);
                }

            }


            $where = array('id'=>$id);
            $this->admin_model->update($data,$where);
            $alerts = array('success' => '编辑管理员成功');
            $this->common_jump_url($alerts,'/admin/manage');
        }

        //获取所有的角色
        $this->load->model('role_model');
        $condition['name <>']='超级管理员';
        $data['roles'] = $this->role_model->findAll($condition);
        
        $this->ct_template->write('_title', '编辑管理员');
        $this->ct_template->write('breadcrum', '编辑管理员');
        $this->ct_template->write_view('content', 'admin/manage/edit', $data, false);
        $this->ct_template->render();
    }


    /**
     * 管理员删除
     * @param $id
     */
    function delete($id)
    {
        $id = intval($id);
        $admin_res=$this->admin_model->find(array('id'=>$id));
        $this->load->model('role_model');
        $role_res=$this->role_model->find(array('id'=>$admin_res['rid']));
        if($role_res['name']==='超级管理员')
        {
            $alerts = array('error' => '超级管理员不能够被删除！');
            $this->common_jump_url($alerts,'/admin/manage');
        }
        if(empty($id) || $id<0){
            $alerts = array('error' => '参数有误，管理员删除失败！');
            $this->common_jump_url($alerts,'/admin/manage');
        }else{
            $where = array('id'=>$id);
            $this->admin_model->delete($where);
            $alerts = array('success' => '管理员删除成功');
            $this->common_jump_url($alerts,'/admin/manage');
        }

    }

    public function set(){
        $this->ct_template->write( '_title', '密码重置' );
        $this->ct_template->write('breadcrum', '密码重置');

        $this->load->library('form_validation');
        $this->load->library('session');
        $this->load->library('CT_auth');
        $uid = $this->session->userdata('admin_uid');

        $data =array();
        $user = $this->admin_model->find( array('id'=>$uid),'username,pass');

        $data['username'] = $user['username'];

        if( $_SERVER['REQUEST_METHOD'] == 'POST' ){

            if( $this->form_validation->run('admin_set') == true ){

                $old_pass = $this->input->post('oldpass');
                $new_pass = $this->input->post('newpass');

                if( $user['pass']!= $this->ct_auth->hashSSHA($old_pass)){

                    $this->form_validation->set_field_error( 'oldpass', '当前密码错误' );
                }else{

                    if($this->admin_model->update( array('pass'=>$this->ct_auth->hashSSHA($new_pass)),array('id'=>$uid) )){

                        redirect('/admin/login/logout');

                    }else{
                        $alerts = array('error' => '密码修改失败！');
                        $this->common_jump_url($alerts,'/admin/manage/set');
                    }
                }
            }
        }

        $this->ct_template->write_view('content', 'admin/manage/set', $data, false);
        $this->ct_template->render();
    }

}
